package com.example.train.common.config.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.example.train.common.config.security.service.DynamicSecurityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.*;

/**
 * 动态权限数据源，用于获取动态权限规则
 */
@Slf4j
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    public final static String ACCESS_SEPARATOR = ":";

    @Autowired
    private DynamicSecurityService dynamicSecurityService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<ConfigAttribute> configAttributes = new ArrayList<>();
        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
//            return SecurityConfig.createList("ROLE_ANONYMOUS");
            return configAttributes;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        boolean present = authorities.stream().anyMatch(l ->
                DynamicAccessDecisionManager.ROLE_ADMIN.equals(l.getAuthority()));
        if (present) {
            return SecurityConfig.createList(DynamicAccessDecisionManager.ROLE_ADMIN);
        }


        Map<String, List<ConfigAttribute>> configAttributeMap = dynamicSecurityService.getConfigAttributeMap();
        //获取当前访问的路径
        FilterInvocation filterInvocation = (FilterInvocation) o;

        String requestUrl = filterInvocation.getRequestUrl();
        String method = filterInvocation.getRequest().getMethod();
        String actualURL = URLUtil.getPath(requestUrl);
        log.debug("current path: {}, actually path: {}",requestUrl,actualURL);

        PathMatcher pathMatcher = new AntPathMatcher();
        Iterator<String> iterator = configAttributeMap.keySet().iterator();
        //获取访问该路径所需资源
        while (iterator.hasNext()) {
            String access = iterator.next();
            String[] accessArr = access.split(ACCESS_SEPARATOR);
            String needPattern = accessArr[0];
            String needMethod = accessArr[1];
            if (pathMatcher.match(needPattern, actualURL) && verifyMethod(method,needMethod)) {
                configAttributes.addAll(configAttributeMap.get(access));
            }
        }

//        if (configAttributes.size() == 0) {
//            return SecurityConfig.createList("ROLE_ANONYMOUS");
//        }

        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    private boolean verifyMethod(String method,String needMethod) {
        if (StrUtil.isEmpty(method) || method.equals(needMethod)) {
            return true;
        }
        return false;
    }

}
